<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage, } from 'element-plus'
import { useRouter } from 'vue-router'
// 当前文件未使用 axios，移除该导入以避免未使用变量警告
import { useUserStore } from '../stores/index'
import { getValidateCodeApi } from '@/api/index'

const router = useRouter()
const userStore = useUserStore()

// 登录表单数据
const loginForm = reactive({
  userName: 'admin', // 提供默认用户名，方便测试
  password: '111111', // 提供默认密码，方便测试

  captcha: '' // 验证码字段
})

// 验证码key
const codeKey = ref('')
// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },

  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },

  ]
}

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>()

// 登录按钮加载状态
const loading = ref(false)

// 验证码图片URL
const captchaUrl = ref('')

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    // 尝试从后端获取验证码
    try {
      const response = await getValidateCodeApi()
      // 假设后端返回的是base64编码的图片数据
      // 如果返回的是图片URL，可以直接设置captchaUrl.value = response.data
      captchaUrl.value = response.data?.codeValue || ''
      // 假设后端返回的数据结构为 { data: { codeKey } }，根据实际情况调整
      codeKey.value = response.data?.codeKey || ''
    } catch (apiError) {
      // 如果API调用失败，使用模拟的验证码图片
      console.warn('API调用失败，使用模拟验证码:', apiError)
      // 这是一个简单的模拟验证码图片的base64编码
      // 实际项目中应该移除这段代码，直接使用后端返回的数据
    }

  } catch (error) {
    ElMessage.error('获取验证码失败，请稍后重试')
    console.error('获取验证码错误:', error)
  }
}

// 处理登录提交
const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate()
  loading.value = true

  // 调用 user 仓库中的登录方法
  await userStore.login({
    ...loginForm,
    codeKey: codeKey.value
  })
  // 显示成功消息
  ElMessage.success('登录成功')

  // 获取URL中的redirect参数
  const redirect = new URLSearchParams(window.location.search).get('redirect')

  // 如果有redirect参数，就重定向到这个URL；如果没有，就重定向到首页
  router.push(redirect || '/')
}

// 处理重置
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}


// 组件挂载时，检查是否有记住的用户名并加载验证码
onMounted(() => {

  refreshCaptcha()
})
</script>

<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-header">
        <h1 class="login-title">SPZX Admin</h1>
        <p class="login-subtitle">管理系统登录</p>
      </div>

      <ElForm ref="formRef" :model="loginForm" :rules="rules" class="login-form" autocomplete="on">
        <ElFormItem prop="userName">
          <ElInput v-model="loginForm.userName" placeholder="请输入用户名" prefix-icon="User"  />
        </ElFormItem>

        <ElFormItem prop="password">
          <ElInput v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
            autocomplete="current-password" />
        </ElFormItem>

        <!-- 验证码输入框 -->
        <ElFormItem prop="captcha">
          <div class="captcha-container">
            <ElInput v-model="loginForm.captcha" placeholder="请输入验证码" prefix-icon="VerificationCode"
              style="width: 65%; margin-right: 10px;" />
            <div class="captcha-image-wrapper">
              <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" class="captcha-image" @click="refreshCaptcha"
                title="点击刷新" />
              <div v-else class="captcha-loading" @click="refreshCaptcha">
                点击获取验证码
              </div>
            </div>
          </div>
        </ElFormItem>



        <ElFormItem>
          <ElButton type="primary" class="w-full" :loading="loading" @click="handleLogin">
            登录
          </ElButton>
        </ElFormItem>

        <ElFormItem>
          <ElButton type="default" class="w-full" @click="handleReset">
            重置
          </ElButton>
        </ElFormItem>
      </ElForm>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-form-wrapper {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.login-header {
  text-align: center;
  margin-bottom: 2rem;
}

.login-title {
  font-size: 2rem;
  font-weight: 700;
  color: #303133;
  margin: 0 0 0.5rem 0;
}

.login-subtitle {
  font-size: 1rem;
  color: #606266;
  margin: 0;
}

.login-form {
  width: 100%;
}

.login-form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper):hover {
  border-color: #409eff;
}

.login-form :deep(.el-button) {
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 1rem;
}

.login-form :deep(.el-checkbox__label) {
  font-size: 0.875rem;
}

/* 验证码样式 */
.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-image-wrapper {
  flex: 1;
  min-height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-image {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.captcha-image:hover {
  transform: scale(1.02);
}

.captcha-loading {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  cursor: pointer;
  color: #606266;
  font-size: 0.875rem;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
}

.captcha-loading:hover {
  border-color: #409eff;
  color: #409eff;
}
</style>